﻿using System;
using System.Xml.Linq;
using FirstFloor.Documents.Annotations;
using FirstFloor.Documents.Annotations.Storage;

namespace FirstFloor.Documents.Presentation.Annotations
{
    /// <summary>
    /// Reads and writes sticky note annotations.
    /// </summary>
    public class StickyNoteFactory
        : AnnotationFactory<StickyNote>
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="StickyNoteFactory"/> class.
        /// </summary>
        public StickyNoteFactory()
            : base(StickyNote.TypeStickyNote)
        {
        }

        /// <summary>
        /// Creates the annotation.
        /// </summary>
        /// <returns></returns>
        public override StickyNote CreateAnnotation()
        {
            return new StickyNote();
        }

        /// <summary>
        /// Reads the specified element.
        /// </summary>
        /// <param name="element">The element.</param>
        /// <returns></returns>
        protected override StickyNote Read(XElement element)
        {
            var note = base.Read(element);
            note.PageNumber = (int)element.Attribute("PageNumber");
            note.Text = (string)element.Attribute("Text");
            note.Left = (double)element.Attribute("Left");
            note.Top = (double)element.Attribute("Top");

            return note;
        }

        /// <summary>
        /// Writes the specified annotation.
        /// </summary>
        /// <param name="annotation">The annotation.</param>
        /// <returns></returns>
        protected override XElement Write(StickyNote annotation)
        {
            var element = base.Write(annotation);
            element.Add(
                new XAttribute("PageNumber", annotation.PageNumber),
                new XAttribute("Text", annotation.Text ?? string.Empty),
                new XAttribute("Left", annotation.Left),
                new XAttribute("Top", annotation.Top));

            return element;
        }

        /// <summary>
        /// Creates a new sticky note annotation for the viewer control associated with the specified <see cref="AnnotationService"/>.
        /// </summary>
        /// <param name="service">The service.</param>
        public StickyNote CreateStickyNote(AnnotationService service)
        {
            if (service == null || !service.IsEnabled) {
                throw new InvalidOperationException();
            }

            service.Store.BeginEdit();

            // create new sticky note
            var note = new StickyNote() {
                PageNumber = service.TextContainer.PageNumber
            };

            service.Store.Add(note);
            service.Store.EndEdit();

            return note;
        }
    }
}
